package com.share.algorithm.rescursive;

/**
 * @desc: 阶乘递归
 * @author:caifan
 * @date:2020/8/9
 */
public class MutilRescursive {

    /**
     * 阶乘 使用普通递归
     * @param n
     * @return
     */
    public static Integer factorial(Integer n) {
        if (n < 0) {
            return 0;
        }
        if (n <= 2) {
            return n;
        }
        return n * factorial(n - 1);
    }

    /**
     * 使用尾递归 从最后面开始计算 将值往前传递 f(10, 1) f(9, 10) f(8, 90)...
     * @param n 值
     * @param result 深度对应的结果
     * @return
     */
    public static Integer tailFactorial(Integer n, Integer result) {
        if (n <= 0) {
            return 1 * result;
        } else {
            return tailFactorial(n - 1, n * result);
        }
    }

    /**
     * 递归使用循环优化
     * @param n
     * @return
     */
    public static Integer factorialLoop(Integer n) {
        Integer result = 1;
        for (int i=1;i<=n;i++) {
            result = result * i;
        }
        return result;

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println(factorial(15));
        System.out.println("耗时：" + (System.currentTimeMillis() - start) + "ms");
        long start1 = System.currentTimeMillis();
        System.out.println(tailFactorial(15, 1));
        System.out.println("耗时：" + (System.currentTimeMillis() - start1) + "ms");
        System.out.println(factorialLoop(15));
    }

}
